<template>
  <div class="submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">{{$t('submitOrder.submitOrder')}}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">step 01.</div>
            <div class="text">{{$t('submitOrder.selectProductToBuy')}}</div>
          </div>
          <div class="item active">
            <div class="number">step 02.</div>
            <div class="text">{{$t('submitOrder.confirmOrderInformation')}}</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">{{$t('submitOrder.payToCompleteTheOrder')}}</div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('address.receivingAddress')}}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              :class="['item', address.commonAddr?'default-address':'',selectedAddrId==address.addrId?'active':'']"
              v-for="address in addressList"
              :key="address.addrId"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{address.receiver}}</span>
                <span class="phone">{{address.mobile}}</span>
                <span
                  class="set-default"
                  v-if="!address.commonAddr"
                  @click="setDefaultAddr(address.addrId)"
                >{{$t('address.setDefault')}}</span>
                <span class="default-tag" v-if="address.commonAddr">{{$t('address.default')}}</span>
              </div>
              <div
                class="address-detail"
              >{{address.province+address.city+address.area+address.addr}}</div>
              <div class="del-edit">
                <span class="edit" @click.stop="editAddr(address.addrId)"></span>
                <span class="del" @click.stop="toggleDelAddr(true,address.addrId)"></span>
              </div>
            </div>
            <div class="item add-address" @click="toggleAddrPop(true)">
              <div class="add-box">
                <div class="img">+</div>
                <div class="text">{{$t('address.addAddress')}}</div>
              </div>
            </div>
          </div>
          <div class="popup-mask" v-if="showDelAddr"></div>
          <div class="fix-transform-blur">
            <div class="popup-box" v-if="showDelAddr">
              <div class="tit" style="padding:10px;">
                <div class="text">{{$t('tips')}}</div>
                <div class="close" @click="toggleDelAddr(false)"></div>
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning"></div>
                  <div class="tip-info">
                    <div class="result">{{$t('address.deleteShippingAddress')}}</div>
                    <div class="date">{{$t('address.deleteShippingTips')}}</div>
                    <div class="btns">
                      <a href="javascrip:void(0);" @click="delAddr()" class="btn-r">{{$t('delete')}}</a>
                      <a href="javascrip:void(0);" @click="toggleDelAddr(flase)" class="btn-g">{{$t('cancel')}}</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('commonFoot.paymentMethod')}}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">{{$t('submitOrder.payOnline')}}</div>
            <!-- <div class="item">货到付款</div>
            <div class="item">线下支付</div>-->
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 配送方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('submitOrder.deliveryMethod')}}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">{{$t('submitOrder.courierDelivery')}}</div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 商品信息 -->
        <div class="submit-box goods-info">
          <div class="tit">
            <span class="text">{{$t('applyReturn.productInformation')}}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">&nbsp;</div>
              <div class="info">{{$t('products')}}</div>
              <div class="unit-price">{{$t('priceOne')}}</div>
              <div class="freight">{{$t('submitOrder.shippingFee')}}</div>
              <div class="number">{{$t('quantity')}}</div>
              <div class="total">{{$t('subtotal')}}</div>
            </div>
            <div class="msg-con">
              <!-- 店铺中的商品 -->
              <div class="goods-box">
                <div class="img">
                  <a :href="'/member-center/integral-det/'+productItemDto.prodId" class="img-box">
                    <img :src="productItemDto.pic" alt />
                  </a>
                </div>
                <div class="info">
                  <a :href="'/member-center/integral-det/'+productItemDto.prodId" class="name">{{productItemDto.prodName}}</a>
                  <span class="sku">{{productItemDto.skuName}}</span>
                </div>
                <div class="unit-price" >
                  <span v-if="productItemDto.price > 0">￥{{parsePrice(productItemDto.price)[0]}}.{{parsePrice(productItemDto.price)[1]}} +</span> {{productItemDto.scorePrice/productItemDto.prodCount}}&nbsp;积分
                </div>
                <div
                  class="freight"
                >￥{{parsePrice(orderInfo.transfee)[0]}}.{{parsePrice(orderInfo.transfee)[1]}}</div>
                <div class="number">{{productItemDto.prodCount}}</div>
                <div class="total"><span v-if="productItemDto.productTotalAmount > 0">￥{{parsePrice(productItemDto.productTotalAmount)[0]}}.{{parsePrice(productItemDto.productTotalAmount)[1]}} +</span> {{productItemDto.scorePrice}}&nbsp;积分</div>
              </div>

              <!-- 留言 -->
              <div class="submit-box">
                <div class="remakes">
                  {{$t('submitOrder.noteMessage')}}：<input type="text" maxlength="100" class="text" v-model="remarks" placeholder="选填" />
                </div>
              </div>
              <!-- /留言 -->
            </div>
          </div>
        </div>
        <!-- 商品信息 -->
      </div>
      <div class="submit-bottom">
        <div class="statistic-box">
          <div class="item">
            <div class="tit">
              <span class="number">{{orderInfo.totalCount}}</span>{{$t('submitOrder.totalItems')}}：
            </div>
            <div class="con">
              <span v-if="orderInfo.total > 0">￥{{parsePrice(orderInfo.total)[0]}}.{{parsePrice(orderInfo.total)[1]}} +</span> {{productItemDto.scorePrice}}&nbsp;{{$t('submitOrder.points')}}
            </div>
          </div>
          <div class="item">
            <div class="tit">{{$t('submitOrder.freightPayable')}}：</div>
            <div
              class="con"
            >+￥{{parsePrice(orderInfo.totalTransfee)[0]}}.{{parsePrice(orderInfo.totalTransfee)[1]}}</div>
          </div>
          <div class="item">
            <div class="tit">{{$t('submitOrder.offerAmount')}}：</div>
            <div
              class="con"
            >-￥{{parsePrice(orderInfo.orderReduce)[0]}}.{{parsePrice(orderInfo.orderReduce)[1]}}</div>
          </div>
        </div>

        <div class="detail-box">
          <div class="item">
            <div class="tit">{{$t('submitOrder.totalPayable')}}：</div>
            <div class="con">
              <span v-if="orderInfo.actualTotal > 0">￥{{parsePrice(orderInfo.actualTotal)[0]}}.{{parsePrice(orderInfo.actualTotal)[1]}} +</span>  {{productItemDto.scorePrice}}&nbsp;{{$t('submitOrder.points')}}
            </div>
          </div>
          <div class="item" v-if="currentAddr.addrId">
            <span
              class="text"
            >{{$t('submitOrder.sendTo')}}：{{currentAddr.province+' '+currentAddr.city +' '+currentAddr.area+' '+currentAddr.addr}}</span>
            <span class="text">{{$t('submitOrder.consignee')}}：{{currentAddr.receiver}} {{currentAddr.mobile}}</span>
          </div>
        </div>
        <div class="btn-box">
          <a href="javascript:void(0)" class="btn" @click="submitOrder">{{$t('submitOrder.submitOrder')}}</a>
        </div>
      </div>
    </div>
    <!-- 地址弹窗 -->
    <AddressPop
      :editAddrId="editAddrId"
      v-if="showAddrPop"
      @getAddrList="getAddrList"
      @reloadOrderInfo="loadOrderInfo"
      @toggleAddrPop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
  </div>
</template>

<script>
import AddressPop from '~/components/add-or-edit-address'
import CouponSelect from '~/components/coupon-select'
export default {
  components: {
    AddressPop, CouponSelect
  },
  data () {
    return {
      addressList: [],
      selectedAddrId: 0,
      orderInfo: {},
      productItemDto: [],
      remarks: '', //留言

      // 积分相关
      totalScoreAmount: 0,  // 积分抵扣金额
      totalUsableScore: 0,  // 整个订单可以使用的积分数
      isScorePay: 0,  // 用户是否选择积分抵现(0不使用 1使用 默认不使用)
      isChecked: true,  // 是否选择会员积分抵现
      isProhibit: false,  // （积分抵现）checkbox是否禁止

      // 地址数据
      currentAddr: {}, // 当前选择的地址
      showAddrPop: false, // 地址弹窗显隐
      editAddrId: 0, // 要修改的地址id
      showDelAddr: false,

      // 券
      orderEntry: 0, //订单入口 0购物车 1立即购买
      uuid: ''
    }
  },
  mounted () {
    if (this.$route.query.orderEntry) {
      this.orderEntry = this.$route.query.orderEntry
    }
    this.uuid = this.genUUID();
    this.getAddrList()
    this.loadOrderInfo()
  },
  methods: {

    /**
     * 获取地址列表
     */
    getAddrList () {
      this.$axios.get('/p/address/list').then(({ data }) => {
        this.addressList = data
      })
    },

    /**
     * 选择地址
     */
    changeAddress (addrId) {
      this.addressList.forEach(element => {
        if (element.addrId == addrId) {
          this.currentAddr = element
        }
      });
      this.selectedAddrId = addrId
      this.loadOrderInfo()
    },

    /**
     * 设置为默认地址
     */
    setDefaultAddr (addrId) {
      this.$axios.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.getAddrList()
      })
    },
    /**
     * 显示/隐藏确认删除弹窗
     */
    toggleDelAddr (sts, addrId) {
      this.showDelAddr = sts
      this.editAddrId = addrId
    },
    /**
     * 显示/隐藏地址弹窗
     */
    toggleAddrPop (sts) {
      this.showAddrPop = sts
      this.editAddrId = 0
    },

    /**
     * 修改地址 (弹窗传地址id)
     */
    editAddr (addrId) {
      this.showAddrPop = true
      this.editAddrId = addrId
    },
    /**
     * 删除地址
     */
    delAddr () {
      let reload = false
      if (this.selectedAddrId == this.editAddrId) {
        this.selectedAddrId = 0
        reload = true
      }
      this.$axios.delete('/p/address/deleteAddr/' + this.editAddrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.toggleDelAddr(false)
        this.getAddrList()
        if (reload) {
            this.loadOrderInfo()
        }
      })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },

    /**
     * 加载订单数据
     */
    loadOrderInfo () {
      // const loading = this.$loading({
      //   lock: true,
      //   text: '加载中...',
      //   background: 'rgba(255, 255, 255, 0.8)'
      // });
      var orderParam = {
        addrId: this.selectedAddrId,
        orderItem: this.orderEntry == 1 ? JSON.parse(sessionStorage.getItem("orderItem")) : undefined,
        basketIds: this.orderEntry == 0 ? JSON.parse(sessionStorage.getItem("basketIds")) : undefined,
        // isScorePay: this.isScorePay,
        userChangeCoupon: 1,
        uuid: this.uuid
      }
      this.$axios.post('/p/score/confirm', orderParam).then(({ data }) => {
        this.orderInfo = data
        this.productItemDto = data.productItemDto
        if (data.userAddr) {
          this.currentAddr = data.userAddr
          this.selectedAddrId = data.userAddr.addrId
        }
        // loading.close();
      }).catch(() => {
        // loading.close();
      })
    },

    /**
     * 提交订单
     */
    submitOrder () {
      if (!this.addressList.length) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'success',
          duration: 1000
        })
        this.showAddrPop = true
        return
      }
      if (this.selectedAddrId == 0) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'success',
          duration: 1000
        })
        document.body.scrollTop = document.documentElement.scrollTop = 0
        return
      }
      this.$axios.post('/p/score/submit', {
        remarks: this.remarks,
        uuid: this.uuid
      }).then(({ data }) => {
        sessionStorage.setItem("pay_total", this.orderInfo.actualTotal)
        sessionStorage.setItem("pay_orderNumber", data.orderNumbers)
        this.$router.push({
          path: '/payment'
        })
      })

    },

    /**
     * 生成uuid
     */
    genUUID () {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    }
  }
}
</script>

<style scoped src='~/assets/css/submit-order.css'></style>
<style scoped>
.fix-transform-blur {
  z-index: 10000;
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
}

.submit-order .submit-box {
  padding-left: 20px;
}
.submit-order .submit-box .goods-msg .msg-con {
  background: #f9f9f9;
  margin-top: 0;
  padding-bottom: 30px;
  border-bottom: 1px solid #eee;
}

.submit-order .statistic-box .item .con, 
.submit-order .detail-box .item .con {
  min-width: 120px;
  width: auto;
}

.submit-order .submit-box .goods-msg .msg-con .goods-box {
  margin: 0 15px;
}

.submit-order .submit-box .goods-msg .msg-con .goods-box::after {
  left: 0;
  right: 0;
}

.submit-order .submit-box .goods-msg .msg-tab .img,
.submit-order .submit-box .goods-msg .msg-con .img {
  padding: 0 15px 0 0;
}

.submit-order .submit-box .remakes {
  margin-top: 15px;
}

.submit-order .submit-box .remakes .text {
  margin-left: 0;
}
.submit-order .statistic-box .item {
  min-height: 33px;
  line-height: 33px;
}
.score-pri {
  line-height: 1.5em!important;
}
</style>